package avicit.bdp.dgs.qa.service.algo.raw.data.pcm.utils;

import avicit.platform6.core.exception.BusinessException;
import io.minio.DownloadObjectArgs;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2023-11-01
 * @类说明：S3Utils
 * @修改记录：
 * @注意事项：
 * @主要功能：S3通用算法
 */
public class S3Utils {
    private static final Logger logger = LoggerFactory.getLogger(S3Utils.class);

    /**
     * 从OSS下载文件到本地
     *
     * @param endpoint
     * @param accessKey
     * @param secretKey
     * @param bucketName
     * @param objectName
     * @param localFilePath
     */
    public static void download(String endpoint, String accessKey, String secretKey,
                                String bucketName, String objectName, String localFilePath) {
        try {
            MinioClient s3Client = getMinioClinet(endpoint, accessKey, secretKey);
            s3Client.downloadObject(DownloadObjectArgs.builder().bucket(bucketName).object(objectName).filename(localFilePath).build());
        } catch (Exception e) {
            logger.error(String.format("下载文件[%s]到本地失败.", objectName), e);
            throw new BusinessException(String.format("下载文件[%s]到本地失败.", objectName));
        }
    }

    /**
     * 获取OSS中对象流
     *
     * @param endpoint
     * @param accessKey
     * @param secretKey
     * @param bucketName
     * @param objectName
     * @return
     */
    public static InputStream getMinioObject(String endpoint, String accessKey, String secretKey, String bucketName, String objectName) {

        InputStream inputStream;
        try {
            MinioClient s3Client = getMinioClinet(endpoint, accessKey, secretKey);
            inputStream = s3Client.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            throw new BusinessException(String.format("获取MinIO客户端失败，endPoint:%s,accessKey:%s,secretKey:%s,bucketName:%s,objectName:%s."
                    , endpoint, accessKey,secretKey, bucketName, objectName));
        }

        return inputStream;
    }

    /**
     * 获取MinIO客户端
     *
     * @param endpoint
     * @param accessKey
     * @param secretKey
     * @return
     */
    public static MinioClient getMinioClinet(String endpoint, String accessKey, String secretKey) {
        MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();

        return minioClient;
    }
}
